package com.lin.linapiinterface.controller;

import com.lin.linapiclientsdk.model.User;
import com.lin.linapiclientsdk.utils.SignUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/name")
public class NameController {
    @GetMapping("/get")
    public String getNameByGet(String name, HttpServletRequest request) {
//        System.out.println(request.getHeader("linhuaixu"));
        return "Get 你的名字是" + name;
    }

    @PostMapping("/")
    public String getNameByPost(@RequestParam String name){
        return "POST 你的名字是"+name;
    }
    @PostMapping("/user")
    public String getUserNameByPost(@RequestBody User user, HttpServletRequest request){
        String accessKey = request.getHeader("accessKey");
        String nonce = request.getHeader("nonce");
        String timestamp = request.getHeader("timestamp");
        String sign = request.getHeader("sign");
        String body = request.getHeader("body");

        System.out.println(accessKey);

        // todo: 实际情况应该是区从数据库中查是否已分配给用户, 同时也要查secretKey
        if (!accessKey.equals("0701e5244d1fb5526188618b53567eb9") ) {
            throw new RuntimeException("无权限");
        }
        // todo；实际情况下随机数可以存到 hashmap 或 redis 中
        if (Long.parseLong(nonce) > 10000) {
            throw new RuntimeException("无权限");
        }
        // todo: 时间和当前时间不能超过5分钟
        // if (timestamp) {}
        // todo: 实际情况是从数据库中查出 secretKey
        String serverSign = SignUtils.genSign(body, "2d97bba2c90baf2db63fa4b8f80c73d2");
        if (!sign.equals(serverSign)) {
            throw new RuntimeException("无权限");
        }
        return "Post 用户名是" + user.getUsername();
    }
}
